package xuyuanjun.paymenthandler.context;
/**
 * 
 * @author Xu Yuanjun
 * 
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import xuyuanjun.paymenthandler.entities.Currency;

public class CurrencySet {
	
	private ConcurrentHashMap<String, Currency> currencies;	
	private Properties exchangeRates;
	
	public CurrencySet() {
		currencies = new ConcurrentHashMap<String, Currency>();
		loadExchageRate();
	}
	
	//load profile to initialize the exchange rate to USD
	private void loadExchageRate() {
		try {
			File exchangeProfile = new File("config/usd_exchange_rate.properties");
			if (exchangeProfile.exists()) {
				exchangeRates = new Properties();			
				exchangeRates.load(new FileInputStream(exchangeProfile));
				for(Map.Entry<Object, Object> a : exchangeRates.entrySet()) {
					String currencyCode = a.getKey().toString();
					double exchangeRate = 0;
					try {
						exchangeRate = Double.parseDouble(a.getValue().toString());
					} catch (NumberFormatException e) {
						System.err.println("Warning: invalid exchange for: " + a.getKey().toString());
					}
					currencies.put(currencyCode, new Currency(currencyCode, exchangeRate));
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public boolean isCurrencyExists(String currencyCode) {
		return currencies.containsKey(currencyCode);
	}
	
	public Currency addCurrency(String currencyCode) {
		if (!currencies.contains(currencyCode)) {	
			//check if the exchangeRate exists, defalut 0
			double exchangeRate = exchangeRates != null ?
								  Double.parseDouble(exchangeRates.getProperty(currencyCode, "0"))
								  : 0;
			currencies.put(currencyCode, new Currency(currencyCode, exchangeRate));
		}
		return currencies.get(currencyCode);
	}
	
	public Currency getCurrency(String currencyCode) {
		return currencies.get(currencyCode);
	}
}
